﻿package com.singlenotion.display.buttons
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import org.casalib.display.CasaMovieClip;
	import org.casalib.display.CasaTextField;
	
	dynamic public class GenericButton extends CasaMovieClip
	{
		protected var _on:Boolean;
		protected var _dimmed:Boolean = false;
		
		public var buttonText:CasaTextField;
		
		public function GenericButton($on:Boolean = true)
		{
			_on = $on;
			addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
		}
		
		protected function init($e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			(_on) ? switchOn() : switchOff();
		}
		
		protected function onPressListener($e:MouseEvent):void 
		{
			gotoAndStop("down");
			dispatchEvent(new Event(ButtonEvents.ON_PRESS, false, true));
		}
		
		protected function onReleaseListener($e:MouseEvent):void 
		{
			gotoAndStop("over");
			dispatchEvent(new Event(ButtonEvents.ON_RELEASE, false, true));
		}
		
		protected function onRollOverListener($e:MouseEvent):void
		{
			gotoAndStop("over");
			dispatchEvent(new Event(ButtonEvents.ON_ROLLOVER, false, true));
		}
		
		protected function onRollOutListener($e:MouseEvent):void
		{
			(_dimmed) ? gotoAndStop("out") : gotoAndStop("up");
			dispatchEvent(new Event(ButtonEvents.ON_ROLLOUT, false, true));
		}
		
		protected function addListeners():void
		{
			addEventListener(MouseEvent.MOUSE_DOWN, onPressListener, false, 0, true);
			addEventListener(MouseEvent.CLICK, onReleaseListener, false, 0, true);
			addEventListener(MouseEvent.MOUSE_OVER, onRollOverListener, false, 0, true);
			addEventListener(MouseEvent.MOUSE_OUT, onRollOutListener, false, 0, true);
		}
		
		protected function removeListeners():void
		{
			removeEventListener(MouseEvent.MOUSE_DOWN, onPressListener);
			removeEventListener(MouseEvent.CLICK, onReleaseListener);
			removeEventListener(MouseEvent.MOUSE_OVER, onRollOverListener);
			removeEventListener(MouseEvent.MOUSE_OUT, onRollOutListener);
		}
		
		public function switchOff():void
		{
			gotoAndStop("out");
			buttonMode = false;
			removeListeners();
		}
		
		public function switchOn():void
		{
			gotoAndStop("up");
			buttonMode = true;
			mouseChildren = false;
			addListeners();
			onRollOutListener(null);
		}
		
		public function disable():void
		{
			visible = false;
		}
		
		public function enable():void
		{
			visible = true;
		}
		
		public function highlight():void
		{
			switchOff();
			gotoAndStop("highlight");
			onRollOverListener(null);
		}
		
		public function set dimmed($val:Boolean):void
		{
			_dimmed = $val;
			($val) ? gotoAndStop("out") : gotoAndStop("up");
		}
		
		public function get on():Boolean { return _on; }
	}
}